package com.jingdianjichi.oss.adapter;


import com.jingdianjichi.oss.entity.FileInfo;
import com.jingdianjichi.oss.util.MinioUtil;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.net.URLEncoder;
import java.util.List;

public class MinioStorageAdapter implements StorageAdapter {

    @Autowired
    private MinioUtil minioUtil;

    /**
     * minioUrl
     */
    @Value("${minio.url}")
    private String url;


    @Override
    @SneakyThrows  // lombok提供，自动抛出异常，减少throws的使用
    public void createBucket(String bucket) {
        minioUtil.createBucket(bucket);
    }

    @Override
    @SneakyThrows
    public void uploadFile(MultipartFile uploadFile, String bucket, String objectName) {
        minioUtil.createBucket(bucket);
        if(objectName!=null){
            minioUtil.uploadFile(uploadFile.getInputStream(),bucket,
                    objectName+"/"+uploadFile.getOriginalFilename());
        }else{
            minioUtil.uploadFile(uploadFile.getInputStream(),bucket,
                    "/"+uploadFile.getOriginalFilename());
        }
    }

    @Override
    @SneakyThrows
    public List<String> getAllBuckets() {
        return minioUtil.getAllBuckets();
    }

    @Override
    @SneakyThrows
    public List<FileInfo> getAllFile(String bucket) {
        return minioUtil.getAllFile(bucket);
    }

    @Override
    @SneakyThrows
    public InputStream downloadFile(String bucket, String objectName) {
        return minioUtil.downloadFile(bucket,objectName);
    }

    @Override
    @SneakyThrows
    public void deleteBucket(String bucket) {
        minioUtil.deleteBucket(bucket);
    }

    @Override
    @SneakyThrows
    public void deleteFile(String bucket, String objectName) {
        minioUtil.deleteFile(bucket,objectName);
    }

    @Override
    @SneakyThrows
    public String getUrl(String bucket, String objectName) {
        // 使用minio/mc突破minio的图片七天限制，只需要 地址/桶/文件相对路径 即可访问，无须额外后缀
        // 将字符串转换为 URL 编码，因为url不支持中文字符串
        String encodedObjectName = URLEncoder.encode(objectName, "UTF-8");
        return url + "/" + bucket + "/" + encodedObjectName;

        // minio上传图片有七天限制，未突破限制的图片链接非常长，需要带上时间戳等后缀
        //return minioUtil.getPreviewFileUrl(bucket,objectName);
    }


}
